jQuery(function(){
	
	//获取当前合同的泵数据 服务器分页
    var serverDeviceData = {};
    serverDeviceData.contractID=jQuery('#contractID').val();
    var serverDeviceTable;
    jQuery(document).ready(function () {
	serverDeviceTable = jQuery('#resultDeviceTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "iDisplayLength":5,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url":window.rootPath+ '/ui/afterSalePlan/getDevice',
            "data": function (d) {
                return $.extend({}, d, serverDeviceData);
            }
        },
        columns: [
            {
            	data: null
            },
            {
	            data:null,
			    defaultContent: "",
			    render: function(data, type, full, meta){
		    		var operate ='<button type="button" class="btn btn-sm btn-info editBtn" >方案维护</button>';
						
		    		return operate;
						
				}
            },
            {
                data: 'productModel'
            },
            {
            	data: 'productType'
            },
            {
                data: 'productName'
            },
            {
            	data: 'subDivideType'
            },
            {
                data: 'leaveFactoryCode'
            },
            {
                data: 'leaveFactoryDate',
                render: function (data, type, full, meta) {
                    if (data)
                        return moment(data).format('YYYY/MM/DD');
                    else
                        return '';
                }
            },
            {
            	data: null,
                render: function (data, type, full, meta) {
                	var dOut;
                    if (data.maintainSchemeID!=null&&data.maintainSchemeID!=""){
                    	dOut ='<p><span class="badge" style="background-color:blue;font-family:arial;color:bule">有</span></p>';
                    }else{
                    	dOut ='<p><span class="badge" style="background-color:red;font-family:arial;color:bule">无</span></p>';
                    }
                    return dOut;
                }
            }
            ],
        "drawCallback": function (oSettings) {
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

            for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                k++;
            }
            
            serverDeviceTable.off('click','tr');
            serverDeviceTable.on( 'click', 'tr', function (event) {
                event=event||window.event;
                var target=event.target||event.scrElement;
                var data = serverDeviceTable.row( this ).data();

                if(target.className.indexOf('editBtn')!=-1){
               
                    editModule(data);
                }

                return;
            } );
        }
    });
    });
	var editModule=function(data){
        if(!data) return;
        var deviceId = data.id;
        var schemeID = data.maintainSchemeID;
        var leaveFactoryCode = "";
        if (data.leaveFactoryCode!=null){
        	leaveFactoryCode = data.leaveFactoryCode;
        	jQuery('#leaveFactoryCode').val(leaveFactoryCode);
        }
        console.log(jQuery('#leaveFactoryCode').val())
        jQuery('#showCode').val('(设备型号：'+leaveFactoryCode+')');
        jQuery('#deviceID').val(deviceId);
        if (schemeID==null||schemeID==""){
        	jQuery('#selectDeviceID').val(deviceId);
            jQuery('#selectSchemeModal').modal('show');
        }
        serverItemData.deviceID=deviceId;
    	serverItemTable.draw();
	};
	
	/*//保存选中的维护方案(改用按钮直接选择)
    jQuery('.saveSelectBtn').on('click',function(){
        var deviceID =jQuery('#selectDeviceID').val();
        if (deviceID==null||deviceID==""){
        	alert("设备或不存在，请刷新后重试！");
        	jQuery('#selectSchemeModal').modal('hide');
        	return;
        }
        var selects=getSelect("#resultSchemeTable",1);
		   if(selects.length>1){
			   $.springLemonDialog({
			         content: '只能选择一条方案',// 确认文本
			         clickButton: function (sender, modal, index) {// 按钮事件处理
			             $(this).closeDialog(modal);
			         }
			   }); 
		   }
		   else if(selects.length==0){
			   $.springLemonDialog({
			         content: '请选择要引用的方案',// 确认文本
			         clickButton: function (sender, modal, index) {// 按钮事件处理
			             $(this).closeDialog(modal);
			         }
			   }); 
		   }else if(selects.length==1){
               var contractID=jQuery('#contractID').val();
			 var schemeID = selects[0].id;
			 var url=window.rootPath+"/ui/afterSalePlan/selectScheme/"+deviceID+"/"+schemeID+"/"+contractID;
				jQuery.ajax({
					url:  encodeURI(url),
					cache:false,
		            type: 'get',
		            dataType: 'json',
		            success: function (data) {
		            	jQuery('#selectSchemeModal').modal('hide');
                        jQuery('#deviceID').val(deviceID);
                        serverItemData.deviceID=deviceID;
		            	serverItemTable.draw();
		            	serverDeviceData.contractID=jQuery('#contractID').val();
		            	serverDeviceTable.draw();
                        serverPlanData.contractID=contractID;
                        serverPlanTable.draw();
		            }
				});
		   }
    });*/

    //获取当前合同的所有维护计划 服务器分页
    var serverPlanData = {};
    serverPlanData.contractID=jQuery('#contractID').val();
    var serverPlanTable;
    jQuery(document).ready(function () {
        serverPlanTable = jQuery('#planTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "iDisplayLength":5,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/afterSalePlan/getPlans',
                "data": function (d) {
                    return $.extend({}, d, serverPlanData);
                }
            },
            columns: [
                {
                    data: null
                },
                {
                    data: 'leaveFactoryCode'
                },
                {
                    data: 'startDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data: 'maintainPeriod'
                },
                {
                    data: 'maintainProject'
                },
                {
                    data: 'announcement'
                },
                {
                    data: 'memo'
                }
            ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }
            }
        });
    });
    
  //获取方案数据 服务器分页
    var serverSchemeData = {};
    serverSchemeData.deviceID="all";
    var serverSchemeTable;
    jQuery(document).ready(function () {

	serverSchemeTable = jQuery('#resultSchemeTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "iDisplayLength":5,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url":window.rootPath+ '/ui/afterSaleMaintain/getpage',
            "data": function (d) {
                return $.extend({}, d, serverSchemeData);
            }
        },
        columns: [
            {
            	data: null
            },
            {
            	data : null,
				defaultContent : "",
				render : function(data,type, full, meta) {
					var operate = '<button type="button" class="btn btn-info btn-sm selectBtn">选择</button>';
					return operate;
				}
            },
            {
                data: 'schemeName'
            },
            {
            	data: 'schemeCode'
            },
            {
                data: 'type'
            },
            {
                data: 'deviceType'
            }
            ],
        "drawCallback": function (oSettings) {
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

            for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                k++;
            }
            serverSchemeTable.off('click', 'tr');
            serverSchemeTable.on('click','tr',function(event) {
		    event = event|| window.event;
			var target = event.target|| event.scrElement;
			var data = serverSchemeTable.row(this).data();
			if (target.className.indexOf('selectBtn') != -1) {
				selectScheme(data);
			}
			return;
			});
        }
    });
	
	//选择方案
	    var selectScheme=function(data){
		    var deviceID =jQuery('#selectDeviceID').val();
	        if (deviceID==null||deviceID==""){
	        	alert("设备或不存在，请刷新后重试！");
	        	jQuery('#selectSchemeModal').modal('hide');
	        	return;
	        }
	        jQuery(".selectBtn").attr("disabled", true);
	        var contractID=jQuery('#contractID').val();
		    var schemeID = data.id;
			var url=window.rootPath+"/ui/afterSalePlan/selectScheme/"+deviceID+"/"+schemeID+"/"+contractID;
			jQuery.ajax({
				url:  encodeURI(url),
				cache:false,
			    type: 'get',
			    dataType: 'json',
			    success: function (data) {
			        jQuery('#selectSchemeModal').modal('hide');
	                jQuery('#deviceID').val(deviceID);
	                serverItemData.deviceID=deviceID;
			        serverItemTable.draw();
			        serverDeviceData.contractID=jQuery('#contractID').val();
			        serverDeviceTable.draw();
	                serverPlanData.contractID=contractID;
	                serverPlanTable.draw();
	                jQuery(".selectBtn").attr("disabled", false);
			    }
			});
	   }
	
	//查询
    jQuery('.searchSchemeBtn').on('click',function(){
        serverSchemeData.key=jQuery('#keyScheme').val();
        serverSchemeTable.draw();
    });
    
    //撤销查询
    jQuery('.resetSchemeBtn').on("click",function(){
        jQuery('#keyScheme').val('');
        serverSchemeData.key ='';
        serverSchemeTable.draw();
    });
   
});
    

  //获取当前泵的维护计划 服务器分页
    var serverItemData = {};
    serverItemData.deviceID=jQuery('#deviceID').val();
    var serverItemTable;
    jQuery(document).ready(function () {
	serverItemTable = jQuery('#resultItemTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "iDisplayLength":5,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url":window.rootPath+ '/ui/afterSalePlan/getDeviceItem',
            "data": function (d) {
                return $.extend({}, d, serverItemData);
            }
        },
        columns: [
            {
            	data: null
            },
            {
	            data: null,
	            defaultContent: "",
	            render: function (data, type, full, meta) {
	            	var id=data.id
	            	var operate ='<input type="checkbox" class="checkchildItem">';
	            	return operate;
	            }   
            },
            {
                data: 'maintainPeriod'
            },
            {
            	data: 'maintainProject'
            },
            {
                data: 'announcement'
            },
            {
                data: 'memo'
            }
            ],
        "drawCallback": function (oSettings) {
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

            for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                k++;
            }
        }
    });


	///新建维护计划，清空弹窗
	jQuery('.addItemBtn').on('click',function(){
		jQuery("#itemId").val('');
        jQuery("#maintainPeriod").val('');
        jQuery("#maintainProject").val('');
        jQuery("#announcement").val('');
        jQuery("#memo").val('');
		jQuery('#maintainItemModal').modal('show');
	});
	
	/////编辑维护计划
   jQuery('.editItemBtn').on('click', function () {
	   var selects=getSelect("#resultItemTable",1);
	   if(selects.length>1){
		   $.springLemonDialog({
		         content: '只能编辑一条记录',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		             $(this).closeDialog(modal);
		         }
		   }); 
	   }
	   else if(selects.length==0){
		   $.springLemonDialog({
		         content: '请选择要编辑的记录',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		             $(this).closeDialog(modal);
		         }
		   }); 
	   }else if(selects.length==1){
		 var itemId=selects[0].id;
		 var maintainPeriod=selects[0].maintainPeriod;
		 var maintainProject=selects[0].maintainProject;
		 var announcement=selects[0].announcement;
		 var memo=selects[0].memo;
		 jQuery("#itemId").val(itemId);
	     jQuery("#maintainPeriod").val(maintainPeriod);
	     jQuery("#maintainProject").val(maintainProject);
	     jQuery("#announcement").val(announcement);
	     jQuery("#memo").val(memo);
	     jQuery('#maintainItemModal').modal('show');
	   }
   	    
   });
	
	//保存维护项目
   jQuery('.saveItemBtn').on('click', function () {
		if(jQuery("#maintainItemAtrrForm") && !jQuery("#maintainItemAtrrForm").Validform({tiptype:3, showAllError:true}).check(false)){
            return;
        };
        if(jQuery("#maintainPeriod") && !jQuery("#maintainPeriod").Validform({tiptype:3, showAllError:true}).check(false)){
            return;
        };
        var contractID=jQuery('#contractID').val();
        var deviceID=jQuery("#deviceID").val();
        if (deviceID==null||deviceID==""){
        	alert("设备或不存在，请选择设备后重试！");
        	jQuery('#maintainItemModal').modal('hide');
        	return;
        }
        var itemId=jQuery("#itemId").val();
        var leaveFactoryCode=jQuery("#leaveFactoryCode").val();
        var maintainPeriod=jQuery("#maintainPeriod").val();
        var maintainProject=jQuery("#maintainProject").val();
        var announcement=jQuery("#announcement").val();
        var memo=jQuery("#memo").val();
        jQuery(".saveItemBtn").attr("disabled", true);
        if (itemId==""){//新增
	        var d = {
	                "contractID": contractID,
	    			"deviceID": deviceID,
	    			"leaveFactoryCode": leaveFactoryCode,
	                "maintainPeriod": maintainPeriod,
	                "maintainProject": maintainProject,
	                "announcement": announcement,
	                "memo": memo
	        };
        }else{
        	var d = {
        			"id": itemId,
	                "contractID": contractID,
	    			"deviceID": deviceID,
	    			"leaveFactoryCode": leaveFactoryCode,
	                "maintainPeriod": maintainPeriod,
	                "maintainProject": maintainProject,
	                "announcement": announcement,
	                "memo": memo
	        };
        }
        var url=window.rootPath+"/ui/afterSalePlan/savePlan";
        jQuery.ajax({
			type : 'post',
			url : encodeURI(url),
			data : JSON.stringify(d),
			dataType : 'json',
			contentType : 'application/json;charset=utf-8',
			success : function(data) {
				jQuery('#maintainItemModal').modal('hide');
                serverItemData.deviceID=deviceID;
            	serverItemTable.draw(true);
                serverPlanData.contractID=contractID;
                serverPlanTable.draw(true);
                if(data.count == 0){
                	serverDeviceTable.contractID=contractID;
                    serverDeviceTable.draw(true);
                }
                $("#checkAllItem").prop("checked", false);
                jQuery(".saveItemBtn").attr("disabled", false);
			}
		});
        /*if (itemId==""){//新增
        	var api = window.rootPath + "/api/maintainItemDevices";
        	var data = {
                    "contractID": contractID,
        			"deviceID": deviceID,
                    "maintainPeriod": maintainPeriod,
                    "maintainProject": maintainProject,
                    "announcement": announcement,
                    "memo": memo
            };
        	jQuery.ajax({
                type: 'post',
                url: api,
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                success: function (data) {
                	jQuery('#maintainItemModal').modal('hide');
                    serverItemData.deviceID=deviceID;
                	serverItemTable.draw(true);
                    serverPlanData.contractID=contractID;
                    serverPlanTable.draw(true);
                }
            });
    	}else{
    		var url = window.rootPath + "/api/maintainItemDevices/" +itemId;
        	var data = {
                    "contractID": contractID,
        			"deviceID": deviceID,
                    "maintainPeriod": maintainPeriod,
                    "maintainProject": maintainProject,
                    "announcement": announcement,
                    "memo": memo
            };
        	jQuery.ajax({
        		url:encodeURI(url),
                type:'patch',
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                success: function (data) {
                	jQuery('#maintainItemModal').modal('hide');
                    serverItemData.deviceID=deviceID;
                	serverItemTable.draw(true);
                    serverPlanData.contractID=contractID;
                    serverPlanTable.draw(true);
                }
            });
    	}*/
	});
        ////删除维护项目
        jQuery('.delItemBtn').on('click', function () {
            var selects=getSelect("#resultItemTable",1);
            var url=window.rootPath+"/ui/afterSalePlan/delItem";
                if(selects.length==0){
                    $.springLemonDialog({
                        content: '请选择删除的记录',// 确认文本
                        clickButton: function (sender, modal, index) {// 按钮事件处理
                            $(this).closeDialog(modal);
                        }
                    });
                }else{
                    var ids=selects[0].id;
                    for(var i=1;i<selects.length;i++){
                        ids += ',' + selects[i].id;
                    }
                    var api=url+"?ids="+ids;
                    $.springLemonDialog({
                        content: '确认删除'+selects.length+'条记录？',// 确认文本
                        clickButton: function (sender, modal, index) {// 按钮事件处理
                            if (index == 0) {
                                jQuery.ajax({
                                    url:encodeURI(api),
                                    cache:false,
                                    type :"get",
                                    dataType:"json",
                                    contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
                                    success:function(data){
                                        if(data.count==0){
                                            serverDeviceTable.draw(false);
                                        }
                                        serverItemTable.draw(false);
                                        serverPlanTable.draw(false);
                                        $("#checkAllItem").prop("checked", false);
                                    }
                                });
                            }
                            $(this).closeDialog(modal);
                        }
                    });
                }
        });

        //列表中的全选
        $("#checkAllItem").click(function(){
            var check = $(this).prop("checked");
            $(".checkchildItem").prop("checked", check);
        });
        
		$('#myTabs a[href="#tab1"]').tab('show');

  });
});
